package test.reflection;

import test.bean.User;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by linshuo on 2018/1/17.
 * <p>
 * 应用场景:
 * 对一个javabean的属性一个一个set时
 * 使用:
 * 填写refName, inputClass, preStr然后直接运行即可
 */
public class SetterGenerate {
    public static void main(String[] args) {
        String refName = "user";
        Class inputClass = User.class;
        String preStr = "myUser.";
        for (String str : generate(refName, inputClass, preStr)) {
            System.out.println(str);
        }
    }

    private static List<String> generate(String refName, Class inputClass, String preStr) {
        Method[] methods = inputClass.getDeclaredMethods();
        List<String> stringList = new ArrayList<>();
        // 类名(包括包名)
        String fullClassName = inputClass.getName();
        // 类名(不含包名)
        String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
        for (Method method : methods) {
            // 方法名
            String methodName = method.getName();
            if (methodName.startsWith("set")) {
                String fieldName = String.valueOf(methodName.charAt(3)).toLowerCase() + methodName.substring(4);
                String getterFunc = "get" + methodName.substring(3) + "()";
                stringList.add(refName + "." + methodName + "(" + preStr + getterFunc + ");");
            }
        }
        return stringList;

    }
}
